package com.xyz.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

// 全局拦截器
@Component
public class Interceptor implements HandlerInterceptor {

    private static final Logger logger = LoggerFactory.getLogger(Interceptor.class);

    // 预处理回调
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // in日志
        comeIn(request.getHeader("X-Real-IP"), request.getRequestURI());
        // 跳过url
        // if (url.contains("/file/readFile/")) {
        //     return true;
        // }
        return true;
    }

    // 后处理回调，preHandle结果为true时调用
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
    }

    // 最终回调，preHandle结果为true时调用
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        comeOut(request.getHeader("X-Real-IP"), request.getRequestURI());
    }

    // come in
    private void comeIn(String ip, String url) {
        logger.info("-----Come In-----" + ip + ">>>" + url);
    }

    // come out
    private void comeOut(String ip, String url) {
        logger.info("-----Come Out-----" + ip + ">>>" + url);
    }

}
